# Import Python's XML parsing class.
from xml.dom import minidom

class HSVOMessageReader():
    """
    HSVO Message Reader
    
    This class parses an HSVO-specific XML string, and provides
    several methods for extracting important information.
    """
    
    # This is used to store the parsed HSVO XML message.
    xmlData = None
    
    def load(self, message):
        """
        load() - This method is responsible for parsing an HSVO 
        XML message and storing it as an instance variable.
        """
        self.xmlData = minidom.parseString(message)
    
    
    def getAction(self):
        """
        getAction() - This method is responsible for returning 
        the HSVO action for the currently loaded message.
        """
        return self.xmlData.documentElement.getAttribute('action')
    
    
    def getSessionID(self):
        """
        getSessionID() - This method is responsible for returning 
        the SAVOIR session ID for the currently loaded message.
        """
        return self.xmlData.documentElement.getAttribute('sessionID')
    
    
    def getSavoirUser(self):
        """
        getSavoirUser() - This method is responsible for returning 
        the SAVOIR user for the currently loaded message.
        """
        return self.xmlData.getElementsByTagName('service')[0].getAttribute('user')
    
    
    def getParameters(self):
        """
        getParameters() - This method is responsible for returning a list of 
        HSVO parameters, where each parameter is represented by a dictionary 
        containing its id, name, unit, and value.
        """
        
        # Build an empty data structure, iterate through all of the message 
        # parameters, appending each and its data, and then return the structure.
        parameters = {}
        for parameter in self.xmlData.getElementsByTagName('parameter'):
            parameters[parameter.getAttribute('id')] = {
                'id': parameter.getAttribute('id'),
                'name': parameter.getAttribute('name'),
                'unit': parameter.getAttribute('unit'),
                'value': parameter.getAttribute('value')}
        
        return parameters
    
    
    def getMessage(self):
        """
        getMessage() - This method is responsible for returning the 
        HSVO XML message currently loaded into this instance.
        """
        
        return self.xmlData